<template>
  <div class="customer-management">
    <el-tabs v-model="activeTab" class="mb-4">
      <el-tab-pane label="客户信息管理" name="info" />
      <el-tab-pane label="客户关怀" name="care" />
    </el-tabs>

    <!-- 客户信息管理 -->
    <div v-if="activeTab === 'info'" class="space-y-6">
      <div class="flex-between mb-4">
        <span class="text-xl font-semibold">客户信息管理</span>
        <el-button type="primary" @click="openAddCustomer">新增客户</el-button>
      </div>
      <el-card class="mb-4">
        <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
          <el-form-item label="客户姓名">
            <el-input v-model="searchInfo.name" placeholder="客户姓名" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="searchInfo.phone" placeholder="联系电话" />
          </el-form-item>
          <el-form-item label="宠物名称">
            <el-input v-model="searchInfo.petName" placeholder="宠物名称" />
          </el-form-item>
          <el-form-item label="宠物品种">
            <el-select v-model="searchInfo.petBreed" placeholder="宠物品种" clearable style="width: 220px">
              <el-option label="金毛犬" value="金毛犬" />
              <el-option label="拉布拉多" value="拉布拉多" />
              <el-option label="泰迪" value="泰迪" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-table :data="displayCustomers" border stripe>
          <el-table-column type="expand">
            <template #default="props">
              <div class="pet-list">
                <template v-if="props.row.pets && props.row.pets.length">
                  <el-card v-for="pet in props.row.pets.filter(p => p.id)" :key="pet.id" class="pet-card">
                    <div class="pet-header">
                      <span class="pet-title">🐾 {{ pet.name }} <span class="pet-breed">({{ pet.breed }})</span></span>
                      <el-button type="primary" link size="small" @click="editPet(props.row, pet)">编辑</el-button>
                      <el-button type="danger" link size="small" @click="deletePet(props.row, pet)">删除</el-button>
                    </div>
                    <div class="pet-info">
                      性别：{{ pet.gender }} ｜ 年龄：{{ pet.ageMonth }}月 ｜ 体重：{{ pet.weightKg }}kg ｜ 健康状况：{{ pet.healthStatus }}
                    </div>
                    <template v-if="pet.vaccines && pet.vaccines.filter(v => v.id).length">
                      <el-table :data="pet.vaccines.filter(v => v.id)" size="small" class="vaccine-table" style="margin-top: 8px;">
                        <el-table-column prop="vaccineName" label="疫苗名称" width="120" />
                        <el-table-column prop="batch" label="批次" width="100" />
                        <el-table-column prop="date" label="接种日期" width="120">
                          <template #default="scope2">
                            {{
                              Array.isArray(scope2.row.date)
                                ? dayjs(new Date(scope2.row.date[0], scope2.row.date[1] - 1, scope2.row.date[2])).format('YYYY-MM-DD')
                                : (scope2.row.date
                                    ? (dayjs(scope2.row.date).isValid() ? dayjs(scope2.row.date).format('YYYY-MM-DD') : scope2.row.date)
                                    : '-')
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100">
                          <template #default="scope2">
                            <el-button type="primary" link size="small"
                              @click="editVaccine(props.row, pet, scope2.row)">编辑</el-button>
                            <el-button type="danger" link size="small"
                              @click="deleteVaccine(props.row, pet, scope2.row)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                    <el-button type="success" link size="small" @click="addVaccine(props.row, pet)">新增疫苗记录</el-button>
                  </el-card>
                </template>
                <el-button type="primary" link @click="addPet(props.row)">新增宠物</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="客户姓名" />
          <el-table-column prop="phone" label="联系电话" />
          <el-table-column prop="address" label="家庭住址" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-button type="primary" link @click="editCustomer(scope.row)">编辑</el-button>
                <el-button type="danger" link @click="onDeleteCustomer(scope.row)">删除</el-button>
                <el-button v-if="!scope.row.isMember" type="success" link @click="onUpgradeToMember(scope.row)">升级为会员</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-if="total > 0" :current-page="currentPage" :page-size="pageSize" :total="total"
          :rows="pageSize" layout="total, prev, pager, next, jumper" @current-change="handlePageChange" />
      </el-card>
    </div>

    <!-- 客户关怀 -->
    <div v-if="activeTab === 'care'" class="space-y-6">
      <div class="flex-between mb-4">
        <span class="text-xl font-semibold">客户关怀与提醒</span>
        <div>
          <el-button type="success" @click="onBatchGenerate">批量生成</el-button>
          <el-button type="primary" @click="onAddCare">新增关怀</el-button>
        </div>
      </div>
      <el-card>
        <el-table :data="displayCares" border stripe>
          <el-table-column prop="customerName" label="客户姓名" />
          <el-table-column prop="petName" label="宠物名称" />
          <el-table-column prop="careType" label="关怀类型" />
          <el-table-column prop="triggerDate" label="触发日期">
            <template #default="scope">
              {{ scope?.row?.triggerDate ? dayjs(scope.row.triggerDate).format('YYYY-MM-DD') : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="sendMethod" label="发送方式">
            <template #default="scope">
              {{ scope?.row?.sendMethod ? scope.row.sendMethod.split(',').join('，') : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="发送状态">
            <template #default="scope">
              <el-tag :type="statusTagType(scope?.row?.status)">{{ scope?.row?.status || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <div class="care-action-bar">
                <el-button class="care-action-btn edit" type="primary" link
                  @click="onEditCare(scope.row)">编辑</el-button>
                <el-button class="care-action-btn send" type="success" link
                  @click="onSendCare(scope.row)">立即发送</el-button>
                <el-button class="care-action-btn delete" type="danger" link
                  @click="onDeleteCare(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="mt-4" :current-page="carePagination.pageNum" :page-size="carePagination.pageSize"
          :total="carePagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleCareSizeChange" @current-change="handleCareCurrentChange" />
      </el-card>
      <!-- 新增关怀弹窗 -->
      <el-dialog v-model="showAddCareModal" title="新增关怀" width="500px">
        <el-form :model="formCare" label-width="100px">
          <el-form-item label="客户姓名">
            <el-select v-model="formCare.customerId" placeholder="请选择客户" filterable @change="onCareCustomerChange">
              <el-option v-for="c in customerStore.customers" :key="c.id" :label="c.name" :value="String(c.id)" />
            </el-select>
          </el-form-item>
          <el-form-item label="宠物名称">
            <el-select v-model="formCare.petId" placeholder="请选择宠物" :disabled="!formCare.customerId">
              <el-option v-for="pet in petsOfSelectedCareCustomer" :key="pet.id" :label="pet.name" :value="String(pet.id)" />
            </el-select>
          </el-form-item>
          <el-form-item label="关怀类型">
            <el-select v-model="formCare.careType" placeholder="请选择">
              <el-option label="生日" value="生日" />
              <el-option label="疫苗" value="疫苗" />
              <el-option label="驱虫" value="驱虫" />
              <el-option label="自定义" value="自定义" />
            </el-select>
          </el-form-item>
          <el-form-item label="触发日期">
            <el-date-picker v-model="formCare.triggerDate" type="date" style="width:100%" />
          </el-form-item>
          <el-form-item label="提前天数">
            <el-input-number v-model="formCare.advanceDays" :min="0" />
          </el-form-item>
          <el-form-item label="发送方式">
            <el-checkbox-group v-model="formCare.sendMethodArr">
              <el-checkbox value="短信">短信</el-checkbox>
              <el-checkbox value="邮件">邮件</el-checkbox>
              <el-checkbox value="微信">微信</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="模板">
            <el-input v-model="formCare.template" type="textarea" :rows="2" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddCareModal = false">取消</el-button>
          <el-button type="primary" @click="onSaveCare">保存</el-button>
        </template>
      </el-dialog>
    </div>

    <!-- 新增/编辑客户弹窗 -->
    <el-dialog v-model="showAddModal" :title="editingCustomer ? '编辑客户信息' : '新增客户信息'" width="600px">
      <el-form ref="customerFormRef" :model="formCustomer" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="客户姓名*" prop="name" :rules="[{ required: true, message: '请输入客户姓名', trigger: 'blur' }]">
              <el-input v-model="formCustomer.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话*" prop="phone" :rules="phoneRules">
              <el-input v-model="formCustomer.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="家庭住址">
          <el-input v-model="formCustomer.address" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="onSaveCustomer">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑宠物弹窗 -->
    <el-dialog v-model="showPetModal" :title="editingPet ? '编辑宠物' : '新增宠物'" width="500px">
      <el-form ref="petFormRef" :model="formPet" label-width="100px">
        <el-form-item label="宠物名称*" prop="name" :rules="[{ required: true, message: '请输入宠物名称', trigger: 'blur' }]">
          <el-input v-model="formPet.name" />
        </el-form-item>
        <el-form-item label="品种">
          <el-input v-model="formPet.breed" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formPet.gender">
            <el-option label="公" value="公" />
            <el-option label="母" value="母" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄(月)">
          <el-input v-model="formPet.ageMonth" type="number" />
        </el-form-item>
        <el-form-item label="体重(kg)">
          <el-input v-model="formPet.weightKg" type="number" step="0.1" />
        </el-form-item>
        <el-form-item label="健康状况">
          <el-input v-model="formPet.healthStatus" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPetModal = false">取消</el-button>
        <el-button type="primary" @click="onSavePet">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑疫苗弹窗 -->
    <el-dialog v-model="showVaccineModal" :title="editingVaccine ? '编辑疫苗记录' : '新增疫苗记录'" width="400px">
      <el-form ref="vaccineFormRef" :model="formVaccine" label-width="90px">
        <el-form-item label="疫苗名称*" prop="vaccineName"
          :rules="[{ required: true, message: '请输入疫苗名称', trigger: 'blur' }]">
          <el-input v-model="formVaccine.vaccineName" />
        </el-form-item>
        <el-form-item label="批次">
          <el-input v-model="formVaccine.batch" />
        </el-form-item>
        <el-form-item label="接种日期*" prop="date" :rules="[{ required: true, message: '请选择接种日期', trigger: 'change' }]">
          <el-date-picker v-model="formVaccine.date" type="date" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showVaccineModal = false">取消</el-button>
        <el-button type="primary" @click="onSaveVaccine">保存</el-button>
      </template>
    </el-dialog>

    <!-- 升级为会员弹窗 -->
    <el-dialog v-model="showUpgradeMemberModal" title="升级为会员" width="500px">
      <el-form :model="upgradeMemberForm" label-width="100px">
        <el-form-item label="会员姓名">
          <el-input v-model="upgradeMemberForm.memberName" />
        </el-form-item>
        <!-- <el-form-item label="联系电话">
          <el-input v-model="upgradeMemberForm.phone" />
        </el-form-item> -->
        <el-form-item label="会员等级">
          <el-select v-model="upgradeMemberForm.memberLevel">
            <el-option label="普通会员" value="普通会员" />
            <el-option label="银卡会员" value="银卡会员" />
            <el-option label="金卡会员" value="金卡会员" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="宠物数量">
          <el-input-number v-model="upgradeMemberForm.petCount" :min="0" />
        </el-form-item>
        <el-form-item label="积分余额">
          <el-input-number v-model="upgradeMemberForm.pointsBalance" :min="0" />
        </el-form-item> -->
        <!-- <el-form-item label="上次消费日期">
          <el-date-picker v-model="upgradeMemberForm.lastConsumptionDate" type="date" style="width:100%" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="showUpgradeMemberModal = false">取消</el-button>
        <el-button type="primary" @click="onConfirmUpgradeMember">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { useCustomerStore } from '@/stores/customerStore';
import { useMemberStore } from '@/stores/memberStore';

const activeTab = ref('info');
const showAddModal = ref(false);
const editingCustomer = ref(null);

const showConsumptionDetail = ref(false);
const currentConsumption = ref(null);
const showAddConsumptionModal = ref(false);
const showAddCareModal = ref(false);

const searchInfo = reactive({ name: '', phone: '', petName: '', petBreed: '' });
const searchCare = reactive({ customerName: '', petName: '', careType: '', status: '' });

const customerPagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const currentPage = ref(1);
const pageSize = ref(10);

const customerStore = useCustomerStore();

// 客户列表数据
const displayCustomers = computed(() => {
  console.log('[View] displayCustomers:', customerStore.customers);
  return customerStore.customers;
});

// 关怀提醒数据
const careReminders = ref([]);
const carePagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const displayCares = computed(() => careReminders.value);

const formCustomer = reactive({
  name: '',
  phone: '',
  address: '',
});

const formCare = reactive({
  name: '',
  phone: '',
  address: '',
  customerId: '',
  petId: '',
  careType: '',
  triggerDate: '',
  advanceDays: 0,
  sendMethod: '',
  sendMethodArr: [],
  template: '',
  status: '未发送',
});
const editingCare = ref(null);

const phoneRules = [
  { required: true, message: '请输入联系电话', trigger: 'blur' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
];
const customerFormRef = ref();

const showPetModal = ref(false);
const editingPet = ref(null);
const formPet = reactive({
  name: '',
  breed: '',
  gender: '',
  ageMonth: '',
  weightKg: '',
  healthStatus: '',
});
const petFormRef = ref();
let currentCustomerForPet = null;

const showVaccineModal = ref(false);
const editingVaccine = ref(null);
const formVaccine = reactive({
  vaccineName: '',
  batch: '',
  date: '',
});
const vaccineFormRef = ref();
let currentPetForVaccine = null;

const showUpgradeMemberModal = ref(false);
const upgradeMemberForm = reactive({
  memberName: '',
  phone: '',
  memberLevel: '普通会员',
  petCount: 0,
  pointsBalance: 0,
  lastConsumptionDate: ''
});

const memberStore = useMemberStore();

// 页面加载时获取客户列表
onMounted(async () => {
  console.log('[View] onMounted 启动 fetchCustomerList');
  await fetchCustomerList();
  fetchCareList();
});

async function fetchCustomerList() {
  console.log('[View] fetchCustomerList 调用');
  const res = await customerStore.fetchCustomers({
    ...searchInfo,
    pageNum: customerPagination.pageNum,
    pageSize: customerPagination.pageSize
  });
  customerPagination.total = res.data?.total || 0;
  console.log('[View] fetchCustomerList 完成, total:', customerPagination.total);
}

async function handlePageChange(val) {
  customerPagination.pageNum = val;
  await fetchCustomerList();
}

async function onSearch() {
  customerPagination.pageNum = 1;
  await fetchCustomerList();
}
async function onReset() {
  Object.keys(searchInfo).forEach(k => searchInfo[k] = '');
  customerPagination.pageNum = 1;
  await fetchCustomerList();
}

function openAddCustomer() {
  editingCustomer.value = null;
  Object.keys(formCustomer).forEach(k => formCustomer[k] = '');
  showAddModal.value = true;
}
function editCustomer(row) {
  Object.keys(formCustomer).forEach(k => formCustomer[k] = row[k] ?? '');
  if (Array.isArray(formCustomer.registerDate)) {
    formCustomer.registerDate = new Date(formCustomer.registerDate[0], formCustomer.registerDate[1] - 1, formCustomer.registerDate[2]);
  }
  editingCustomer.value = row;
  showAddModal.value = true;
}
function closeDialog() {
  showAddModal.value = false;
  editingCustomer.value = null;
  Object.keys(formCustomer).forEach(k => formCustomer[k] = '');
}
async function onDeleteCustomer(row) {
  await ElMessageBox.confirm(`确定要删除客户 ${row.name} 吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  });
  await customerStore.deleteCustomer(row.id);
  ElMessage.success('客户已删除');
  fetchCustomerList();
}
function onSaveCustomer() {
  customerFormRef.value.validate(async (valid) => {
    if (!valid) return;
    if (editingCustomer.value) {
      await customerStore.updateCustomer(editingCustomer.value.id, { ...formCustomer, id: editingCustomer.value.id });
      ElMessage.success('客户信息已更新');
    } else {
      await customerStore.addCustomer({ ...formCustomer });
      ElMessage.success('新增客户成功');
    }
    closeDialog();
    fetchCustomerList();
  });
}

// 宠物相关
function addPet(customer) {
  editingPet.value = null;
  Object.keys(formPet).forEach(k => formPet[k] = '');
  showPetModal.value = true;
  currentCustomerForPet = customer;
}
function editPet(customer, pet) {
  Object.keys(formPet).forEach(k => formPet[k] = pet[k] ?? '');
  if (Array.isArray(formPet.birthDate)) {
    formPet.birthDate = new Date(formPet.birthDate[0], formPet.birthDate[1] - 1, formPet.birthDate[2]);
  }
  editingPet.value = pet;
  showPetModal.value = true;
  currentCustomerForPet = customer;
}
function onSavePet() {
  petFormRef.value.validate(async (valid) => {
    if (!valid) return;
    if (editingPet.value) {
      await customerStore.updatePet(editingPet.value.id, { ...formPet });
      ElMessage.success('宠物信息已更新');
    } else {
      await customerStore.addPet(currentCustomerForPet.id, { ...formPet });
      ElMessage.success('新增宠物成功');
    }
    showPetModal.value = false;
    fetchCustomerList();
  });
}
async function deletePet(customer, pet) {
  if (!pet.id) {
    ElMessage.error('宠物ID无效，无法删除');
    return;
  }
  await ElMessageBox.confirm(`确定要删除宠物 ${pet.name || ''} 吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  });
  await customerStore.deletePet(pet.id);
  ElMessage.success('宠物已删除');
  fetchCustomerList();
}

// 疫苗相关
function addVaccine(customer, pet) {
  editingVaccine.value = null;
  Object.keys(formVaccine).forEach(k => formVaccine[k] = '');
  showVaccineModal.value = true;
  currentPetForVaccine = pet;
}
function editVaccine(customer, pet, vaccine) {
  Object.keys(formVaccine).forEach(k => formVaccine[k] = vaccine[k] ?? '');
  if (Array.isArray(formVaccine.date)) {
    formVaccine.date = new Date(formVaccine.date[0], formVaccine.date[1] - 1, formVaccine.date[2]);
  }
  editingVaccine.value = vaccine;
  showVaccineModal.value = true;
  currentPetForVaccine = pet;
}
function onSaveVaccine() {
  vaccineFormRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!currentPetForVaccine) {
      ElMessage.error('未找到对应的宠物，无法保存疫苗记录');
      return;
    }
    if (editingVaccine.value) {
      await customerStore.updateVaccine({ ...formVaccine, id: editingVaccine.value.id });
      ElMessage.success('疫苗记录已更新');
    } else {
      await customerStore.addVaccine({ ...formVaccine, petId: currentPetForVaccine.id });
      ElMessage.success('新增疫苗记录成功');
    }
    showVaccineModal.value = false;
    currentPetForVaccine = null;
    fetchCustomerList();
  });
}
async function deleteVaccine(customer, pet, vaccine) {
  await ElMessageBox.confirm(`确定要删除疫苗记录吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  });
  await customerStore.deleteVaccine(vaccine.id);
  ElMessage.success('疫苗记录已删除');
  fetchCustomerList();
}

// 关怀相关
async function fetchCareList() {
  const res = await customerStore.fetchCareList({
    ...searchCare,
    pageNum: carePagination.pageNum,
    pageSize: carePagination.pageSize
  });
  // 兼容后端返回data或list字段
  let list = [];
  if (Array.isArray(res.data?.data)) {
    list = res.data.data;
  } else if (Array.isArray(res.data?.list)) {
    list = res.data.list;
  }
  careReminders.value = list;
  carePagination.total = res.data?.total || 0;
  console.log('[Care] fetchCareList result:', careReminders.value);
  console.log('[Care] carePagination:', carePagination);
  console.log('[Care] res:', res);
}
async function handleCareSizeChange(val) {
  carePagination.pageSize = val;
  await fetchCareList();
}
async function handleCareCurrentChange(val) {
  carePagination.pageNum = val;
  await fetchCareList();
}
function onSaveCare() {
  // 强制同步，防止watch未及时生效
  formCare.sendMethod = Array.isArray(formCare.sendMethodArr) ? formCare.sendMethodArr.join(',') : '';
  console.log('[Care] 保存时sendMethodArr:', formCare.sendMethodArr, 'formCare.sendMethod:', formCare.sendMethod);
  if (editingCare.value) {
    customerStore.updateCare({ ...formCare, id: editingCare.value.id }).then((res) => {
      ElMessage.success('关怀信息已更新');
      fetchCareList();
      showAddCareModal.value = false;
      editingCare.value = null;
      console.log('[Care] 更新关怀:', formCare, res);
    });
  } else {
    customerStore.addCare({ ...formCare }).then((res) => {
      ElMessage.success('新增关怀成功');
      fetchCareList();
      showAddCareModal.value = false;
      editingCare.value = null;
      console.log('[Care] 新增关怀:', formCare, res);
    });
  }
}
async function onDeleteCare(row) {
  await ElMessageBox.confirm(`确定要删除关怀记录吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  });
  const res = await customerStore.deleteCare(row.id);
  ElMessage.success('关怀记录已删除');
  console.log('[Care] 删除关怀:', row.id, res);
  fetchCareList();
}
function onEditCare(row) {
  Object.assign(formCare, {
    customerId: row.customerId ? String(row.customerId) : '',
    petId: row.petId ? String(row.petId) : '',
    careType: row.careType,
    triggerDate: row.triggerDate || '',
    advanceDays: row.advanceDays,
    sendMethod: row.sendMethod || '',
    sendMethodArr: row.sendMethod ? row.sendMethod.split(',') : [],
    template: row.template,
    status: row.status
  });
  if (Array.isArray(formCare.triggerDate)) {
    formCare.triggerDate = new Date(formCare.triggerDate[0], formCare.triggerDate[1] - 1, formCare.triggerDate[2]);
  }
  editingCare.value = row;
  showAddCareModal.value = true;
  console.log('[Care] 编辑关怀:', row);
}
function onSendCare(row) {
  customerStore.sendCare(row.id).then(() => {
    ElMessage.success('关怀已发送');
    fetchCareList();
  });
}
function onBatchGenerate() {
  customerStore.batchGenerateCare({
    careType: '疫苗',
    advanceDays: 7,
    sendMethod: '短信',
    template: '您的宠物疫苗即将到期，请及时接种'
  }).then(() => {
    ElMessage.success('批量生成成功');
    fetchCareList();
  });
}
function statusTagType(status) {
  if (status === '已发送') return 'success';
  if (status === '已排程') return 'warning';
  if (status === '失败') return 'danger';
  return 'info';
}

// 升级会员
function onUpgradeToMember(row) {
  upgradeMemberForm.memberName = row.name;
  upgradeMemberForm.phone = row.phone;
  upgradeMemberForm.petCount = row.pets ? row.pets.length : 0;
  upgradeMemberForm.lastConsumptionDate = dayjs().format('YYYY-MM-DD');
  upgradeMemberForm.pointsBalance = 0;
  upgradeMemberForm.memberLevel = '普通会员';
  upgradeMemberForm.customerId = row.id;
  showUpgradeMemberModal.value = true;
}
function onConfirmUpgradeMember() {
  console.log('[升级会员] customerId:', upgradeMemberForm.customerId, 'memberLevel:', upgradeMemberForm.memberLevel);
  if (!upgradeMemberForm.customerId) {
    ElMessage.error('客户ID为空，无法升级为会员');
    return;
  }
  customerStore.upgradeMember({
    customerId: upgradeMemberForm.customerId,
    memberLevel: upgradeMemberForm.memberLevel
  }).then(() => {
    showUpgradeMemberModal.value = false;
    ElMessage.success('升级为会员成功');
    fetchCustomerList();
  });
}

const total = computed(() => customerPagination.total);

// 新增关怀弹窗宠物联动
const petsOfSelectedCareCustomer = computed(() => {
  const c = customerStore.customers.find(c => c.id === formCare.customerId);
  return c ? c.pets || [] : [];
});

// 新增关怀弹窗客户选择联动
function onCareCustomerChange() {
  fetchCustomerList();
}

// 新增/编辑关怀弹窗的el-checkbox-group绑定用中间变量sendMethodArr，实际提交时join(',')赋值给formCare.sendMethod
const sendMethodArr = ref([]);

watch(() => formCare.sendMethod, (val) => {
  sendMethodArr.value = val ? val.split(',') : [];
});
watch(sendMethodArr, (val) => {
  formCare.sendMethod = val.join(',');
});

// 新增关怀弹窗前，重置formCare和sendMethodArr
function onAddCare() {
  Object.assign(formCare, {
    customerId: '',
    petId: '',
    careType: '',
    triggerDate: '',
    advanceDays: 0,
    sendMethod: '',
    template: '',
    status: '未发送'
  });
  sendMethodArr.value = [];
  editingCare.value = null;
  showAddCareModal.value = true;
}
</script>

<style scoped>
.customer-management {
  padding: 24px;
}

.flex-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.space-y-6>*+* {
  margin-top: 24px;
}

.pet-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px 18px;
  background: #f8fafc;
  border-radius: 8px;
  padding: 4px 0 4px 4px;
}

.pet-card {
  margin-bottom: 0;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 8px 0 #f0f1f2;
  padding: 8px 12px 6px 12px;
  width: auto;
  min-width: 0;
  max-width: 700px;
  margin-right: auto;
}

.pet-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 600;
  margin-bottom: 2px;
}

.pet-title {
  color: #1976d2;
}

.pet-breed {
  color: #888;
  font-size: 13px;
  font-weight: 400;
}

.pet-info {
  font-size: 13px;
  color: #555;
  margin-bottom: 2px;
}

.vaccine-table {
  background: #f9fafb;
  border-radius: 6px;
  margin-bottom: 2px;
}

.pet-card .el-button {
  margin-left: 0;
  margin-right: 8px;
  padding: 0 4px;
}

.care-action-bar {
  display: flex;
  gap: 4px;
  align-items: center;
}

.care-action-btn {
  font-size: 14px;
  padding: 0 6px;
  min-width: 40px;
  transition: color 0.2s, text-decoration 0.2s;
}

.care-action-btn.delete {
  color: #f56c6c !important;
  font-weight: bold;
}

.care-action-btn.delete:hover {
  color: #c40000 !important;
  text-decoration: underline;
}

.care-action-btn.edit:hover {
  color: #1976d2 !important;
  text-decoration: underline;
}

.care-action-btn.send:hover {
  color: #43a047 !important;
  text-decoration: underline;
}
</style>